<template>
  <div>
    <van-nav-bar
      :title="goods.name"
      class="black"
      left-arrow
      @click-left="onClickLeft"
      
    >
      <template #right>
        <van-icon name="search" size="18" @click="jumpToSearch" color="black" />
      </template>
    </van-nav-bar>

    <van-swipe :autoplay="3000">
      <van-swipe-item
        v-for="(item, index) in goods.s_goods_photos"
        :key="index"
        class="swipeBox"
      >
        <div class="swiper"><img :src="item.path" alt="" /></div>
      </van-swipe-item>

      <template #indicator="{ active, total }">
        <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
      </template>
    </van-swipe>
    <div class="sellPirce" v-show="goods.sale_price ">
      <div class="left">
        <h4>特价</h4>
        <p class="price">
          {{ goods.sale_price }} <span>￥{{ goods.price }}</span>
        </p>
      </div>
      <div class="right">
        新店开张<br />
        限时特价
      </div>
    </div>
    
    <div class="content">
       <p v-show="!goods.sale_price" style="font-size:4.2vw;margin: 0; font-size: 30px; margin-left: -2vw;color: red;">
          <span style="font-size:15px;margin:0 -2vw 0 5.5vw;">￥</span> <span >{{ goods.price }}</span>
        </p>
      <ul>
        <li class="top">
          <div class="left">
            <h3>{{ goods.name }}</h3>
            <div class="round">热卖</div>
          </div>
          <span>
            <p>{{ goods.assess }}%</p>
            好评率
          </span>
        </li>
        <p class="title" v-show="goods.desc">推荐理由</p>
        <li class="instroduction"  v-show="goods.desc">
          <p v-for="(item, index) in goods.desc" :key="index">
            {{ index + 1 }}.<span>{{ item }}</span>
          </p>
        </li>
      </ul>
    </div>
    <div class="line"></div>
    <van-cell is-link :title="goods.points" @click="show = !show" class="" />
    <van-action-sheet v-model:show="show">
      <div class="boxcontent">
        <h4>关于购物返积分：</h4>
        <div class="ruleContent">
          1. 回馈金是严选用以回馈用户的代币<br />
          2. 回馈金可与现金1:1抵扣使用 <br />
          3.回馈金使用无门槛，可叠加 <br />
          4.购物即可返还回馈金，用户等级越高，返还比例越高 <br />
          5.本月获取的回馈金，统一在次月25日23:59:59失效，请尽快使用 <br />
          6.可在个人中心--回馈金中查看回馈金资产<br />
          7.部分特殊商品和订单不支持返还回馈金，具体以回馈金的活动说明为准
          <br />
          8.如有疑问，请联系严选在线客服<br />
        </div>
      </div>
    </van-action-sheet>
    <van-cell
      is-link
      title="邮费：单件包邮"
      @click="shoppingShow = !shoppingShow"
      class=""
    />
    <van-action-sheet v-model:show="shoppingShow">
      <div class="boxcontent">
        <h4>免邮，合作仓直发</h4>
        <div class="ruleContent">
          本商品由官方发货，大陆地区免邮费；港澳台地区满500元免邮费，不满500元收取30元邮费；海外地区以下单页提示运费为准
        </div>
      </div>
    </van-action-sheet>
    <div class="line"></div>
    <div
      class="showImg"
      v-for="(item, index) in goods.s_goods_photos"
      :key="index"
    >
      <img :src="item.path" alt="" />
    </div>
    <van-action-sheet v-model:show="cardShow">
      <div class="cardshow">
        <div class="top">
          <div class="goodsImg">
            <img :src="goods.s_goods_photos[0].path" alt="" />
          </div>
          <div class="text">
            <span>￥</span>{{ goods.price }}
            <p>折后价<span>￥</span>{{ goods.sale_price }}起</p>
          </div>
        </div>
        <van-stepper v-model="gooodNum" class="count" />
        <van-button
          color="linear-gradient(to right, #ff6034, #ee0a24)"
          class="admit"
          @click="add"
        >
          确认
        </van-button>
      </div>
    </van-action-sheet>
    <van-action-bar class="bottonNav">
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-badge :content="cardList.length">
        <router-link to="/goodCard">
          <van-action-bar-icon icon="cart-o" text="购物车"
        /></router-link>
      </van-badge>

      <van-action-bar-button
        color="orange"
        type="warning"
        text="加入购物车"
        @click="addCard"
      />
      <van-action-bar-button
        color="red"
        type="danger"
        text="立即购买"
        @click="jumpToOrder"
      />
    </van-action-bar>
  </div>
</template>
<script>
document.documentElement.scrollTop=0
</script>
<script setup>

import { get, otherget, getData, post, put } from "../../utils/request.js";

import { useRoute, useRouter } from "vue-router";

import { reactive, ref ,watch} from "vue";
import { Toast } from "vant";
import { useStore } from "vuex";

const store = useStore();
const route = useRoute();
const router = useRouter();
let goods = ref({});
let show = ref(false);
let shoppingShow = ref(false);
let cardShow = ref(false);
let gooodNum = ref(1);
let defaultAddress = reactive("");
let cardList = ref([]);
let judge = ref(0);
//获取购物车信息
const getCardData = async () => {
 

  const data = {
    project_id: 234,
  };
  let result;
  try {
    result = await getData("/shoppingCart", data);
  } catch (error) {
  }
  if (result.status == 200) {

    cardList.value = result.data.result;
   console.log(cardList.value);
  }
};

// 获取商品信息
const getGoodsData = async () => {
  Toast.loading({
    message: "正在请求数据，请稍后...",
    forbidClick: true,
    duration: 0,
  });

  let result;
  try {
    result = await get(`/goods/${route.params.id}`);
  } catch (error) {
    console.log(error);
    let timer = setTimeout(() => {
      Toast.clear();
      Toast.fail({ message: "请求失败，请刷新本网页", forbidClick: true });
      clearTimeout(timer);
    }, 3000);
  }
  if (result.status == 200) {
    Toast.clear();
    goods.value = result.data.result;
    console.log(goods.value);
    for (let j = 0; j < 100; j++) {
      let res = Math.random() * 100 + 1;
      if (res >= 80) {
        goods.value.assess = Math.floor(res);
        break;
      }
    }
    //推荐理由
    if (goods.value.desc) {
      goods.value.desc = goods.value.desc.split("-");
    }

    //积分
    goods.value.points =
      "购物返积分，最高返： " +
      Math.floor(Number(goods.value.price) / 10) +
      "积分";
  }
  console.log(goods.value.points);
};

const onClickLeft = () => {
  router.go(-1);
};
const jumpToSearch = () => {
  router.push("/search");
};
watch(()=>route.params.id,(newid,oldid)=>{
  if (newid) {
    getGoodsData();
  }
       
},{immediate:true})
const add = () => {
  if (judge.value == 0) {
    console.log(judge.value);
    addCards();
  } else {
    console.log(judge.value);
    addOrder();
  }
};

//添加购物车
const addCards = async () => {
  Toast.loading({
    message: "正在添加商品到购物车，请稍后，请稍后...",
    forbidClick: true,
    duration: 0,
  });
  const data = {
    goods_id: goods.value.id,
    num: gooodNum.value,
    project_id: "234",
  };
  let result;
  let repeat = cardList.value.filter((ele, index) => {
    return goods.value.id == ele.goods_id;
  });
  console.log(repeat[0]);
  if (repeat.length != 0) {
    const data = {
      id: repeat[0].id,
      num: Number(repeat[0].num) + Number(gooodNum.value),
    };
    updateGoods(data);
  } else {
    addGoods(data);
  }
};

//添加订单
const addOrder = () => {
  const data = goods.value
     data.num=gooodNum.value
  
  store.commit("order/setgoodsOrder", data);
  router.push(`/addOrder/${1}`);
};

//当购物车已有该项商品时 调用此方法
const updateGoods = async (data) => {
  const gooodData = {
    num: data.num,
  };
  let result;
  try {
    result = await put(`/shoppingCart/${data.id}`, gooodData);
  } catch (error) {
    let timer = setTimeout(() => {
      Toast.clear();
      Toast.fail({
        message: "添加购物车失败，请稍后重新尝试",
        forbidClick: true,
      });
      clearTimeout(timer);
    }, 3000);
  }
  if (result.status == 200) {
    cardShow.value = false;
    Toast.clear();
    Toast.success({ message: "添加购物车成功", forbidClick: true });
    getCardData();
  }
};
// 当购物车无该项商品时 调用此方法
const addGoods = async (data) => {
  let result;
  try {
    result = await post("/shoppingCart", data);
  } catch (error) {
  
      Toast.clear();
      Toast.fail({
        message: "添加购物车失败，请稍后重新尝试",
        forbidClick: true,
      });
     
   
  }
  if (result.status == 200) {
    cardShow.value = false;
    Toast.clear();
    Toast.success({ message: "添加购物车成功", forbidClick: true });
    getCardData();
  }
};
const jumpToOrder = () => {
  cardShow.value = true;
  judge.value = 1;
  // router.push(`/addOrder/${1}`)
  // const goods_info={
  //      id:goods.value.id,

  // }
};
const addCard=()=>{
  cardShow.value = true;
  judge.value = 0;
  console.log(judge.value = 0);
}
const getDefaultAddress = async () => {
  try {
    result = await getData("/defalutAddress");
  } catch (error) {}
  if (result.status == 200) {
    console.log(result.data);
    defaultAddress = result.data.result;
  }
};
getCardData();
getGoodsData();
</script>

<style lang="scss" scoped>
.line {
  width: 100%;
  height: 1vh;
  background-color: #f5f5f5;
}
.black {
  --van-nav-bar-icon-color: "black";
  position: fixed;
  top: 0;
  width: 100%;
}
.swipeBox {
  margin-top: 46px;
  .swiper {
    width: 100%;
    height: 50vh;
    img {
      width: 100%;
      height: 100%;
    }
  }
}

.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 2px 5px;
  font-size: 12px;
  border-radius: 5px;
  background: rgba(0, 0, 0, 0.1);
}
.sellPirce {
  width: 100%;
  background-color: rgb(250, 30, 50);
  display: flex;
  justify-content: space-between;
  height: 11.09vh;
  align-items: center;
  box-sizing: border-box;
  padding-left: 3vw;
  padding-right: 3vw;
  color: white;
  h4,
  p {
    margin: 0;
  }
  .left {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;

    h4 {
      font-size: 12px;
    }
    p {
      font-size: 7.2vw;
      span {
        text-decoration: line-through;
        font-size: 3.2vw;
      }
    }
  }
  .right {
    font-family: STZhongsong;
  }
}
.content {
  margin: 0 auto;
  
  width: 100%;

background-color: white;
  padding-bottom: 1vh;
  padding-top: 3vh;
  ul {
    width: 100%;
    padding: 0 4vw;
    box-sizing: border-box;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        h3 {
          width: 75vw;

          word-break: break-all;
          margin: 0;
        }
        .round {
          width: 8.53vw;
          height: 2.39vh;
          font-size: 12px;
          margin-top: 1vh;
          text-align: center;
          line-height: 2.39vh;
          border-radius: 12px;
          background-color: rgb(250, 30, 50);
          color: white;
        }
      }
      span {
        text-align: center;
        display: block;

        p {
          margin: 0;
          font-size: 4.2vw;
          color: rgb(250, 30, 50);
        }
      }
    }
    .title {
      margin: 0;
      margin-bottom: 1vh;
      color: #333;
      margin-top: 2vh;
      font-size: 14px;
    }
    .instroduction {
      color: #333;
      width: 100%;

      font-size: 12px;
      background-color: #f3f3f3;
      border: 1px solid #e6e6e6;

      span {
        margin-left: 1vw;
      }
      p {
        margin: 1vh 0;
      }
    }
  }
}
.showImg {
  width: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}
.boxcontent {
  box-sizing: border-box;
  padding-left: 5vw;
  padding-right: 5vw;
  h4 {
    position: relative;
    margin-left: 3.5vw;
  }
  h4::before {
    content: "";
    width: 5px;
    height: 5px;
    position: absolute;
    left: -3.4vw;
    top: 0.8vh;
    border-radius: 50%;
    background-color: red;
  }
  .ruleContent {
    font-size: 4.2vw;
    line-height: 8.4vw;
    color: #7f7f7f;
  }
}
.cardshow {
  width: 100%;
  height: 30vh;
  display: flex;
  justify-content: space-between;
  flex-direction: column;

  .top {
    display: flex;
    align-items: center;
    .goodsImg {
      margin-left: 3vw;
      margin-top: 3vw;
      width: 30vw;
      height: 30vw;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .text {
      margin-left: 1vw;
      color: rgb(231, 50, 50);
      font-size: 4.26vw;
      display: flex;
      align-items: center;
       text-align: center;
      span {
        font-size: 12px;
      }
      p {
        margin-left: 1vw;
        padding: 5px;
        border-radius: 30px;
        height: 3vh;
        background-color: red;
         line-height: 5.26vw;
        color: white;
      }
    }
  }
  .count {
    width: 30vw;
    margin-left: 75vw;
    margin-top: -7vh;
  }
  .admit {
    margin: 0 auto;
    width: 90vw;
    border-radius: 10vw;
  }
}
</style>
